package net.masker.bbtweet;

import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.StreamConnection;


import net.rim.blackberry.api.browser.URLEncodedPostData;
import net.rim.device.api.io.http.HttpProtocolConstants;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiEngine;
import net.rim.device.api.ui.component.Dialog;


class updateManager extends Thread
{
	private static bbtweetProperties properties;
	private static String updateURL = "http://twitter.com/statuses/update.xml";
	
	private void notifyUser(String data)
	{
	  UiEngine ui = Ui.getUiEngine();
	  Screen screen = new Dialog(Dialog.D_OK, "Didn't work", Dialog.OK,
	    Bitmap.getPredefinedBitmap(Bitmap.EXCLAMATION),
	    Manager.VERTICAL_SCROLL);
	  ui.pushGlobalScreen(screen, 1, ui.GLOBAL_QUEUE);
	}
	
	public void run()
	{
		properties = bbtweetProperties.fetch();
		
		if (!properties.isPushStatusUpdate())
			return;
		
		// open stream and post
		try
		{
			URLEncodedPostData post = new URLEncodedPostData("", false);
			post.append("source", "bbtweet");
			post.append("status", properties.getStatusUpdate());
			StreamConnection s = (StreamConnection)Connector.open(updateURL + "&" + post.toString());
			HttpConnection httpConn = (HttpConnection)s;
            httpConn.setRequestProperty(HttpProtocolConstants.HEADER_AUTHORIZATION,"Basic "
            		+ properties.getAuthenticationHash());
            httpConn.setRequestMethod("POST");
            
            int status = httpConn.getResponseCode();
            if (status != HttpConnection.HTTP_OK)
            {
            	notifyUser("bbtweet status update failed!"); 
            }
            
            properties = bbtweetProperties.fetch();
            properties.setPushStatusUpdate(false);
            properties.setStatusUpdate("");
            properties.save();
            
		}
		catch (IOException e) 
        {
        	properties = bbtweetProperties.fetch();
        	properties.setBbtweetStatusMessage(e.toString());
        	properties.save();
        }
	}
}